// 封装通用的 fetch 数据函数
function fetchData(url, onSuccess, onError) {
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      if (data.message === "获取成功") {
        onSuccess(data.data);
      } else {
        console.error("数据获取失败:", data);
      }
    })
    .catch((error) => {
      console.error("数据加载失败:", error);
      if (onError) onError(error);
    });
}

// 封装通用的渲染列表函数
function renderList(container, items, renderItem) {
  container.innerHTML = items.map(renderItem).join("");
}

// 滑条
const nav = document.querySelector('.mainNav');
const underline = document.querySelector('.mainNav .navUnderline');
nav.addEventListener('mouseover', e => {
  if (e.target.tagName === 'A') {
    underline.style.transform = `translateX(${e.target.offsetLeft - 27}px)`;
  }
});

//hover
const icons = document.querySelector('.topIcons .iconEntry')
const upload = document.querySelector('.topIcons .uploadPanel')
let showId
icons.addEventListener('mouseenter', () => {
  upload.style.display = 'block'
})

icons.addEventListener('mouseleave', () => {
  showId = setTimeout(() => upload.style.display = 'none', 500)
})

upload.addEventListener('mouseenter', () => {
  if (showId) {
    clearTimeout(showId)
  }
  upload.style.display = 'block'
})

upload.addEventListener('mouseleave', () => {
  upload.style.display = 'none'
})


const searchInput = document.querySelector('.searchBar form input');
const searchDropdown = document.getElementById('search-suggest');

  // 显示下拉框
  searchInput.addEventListener('focus', function () {
    searchDropdown.classList.add('active');
  });

  // 隐藏下拉框
  searchInput.addEventListener('blur', function () {
    setTimeout(() => {
      searchDropdown.classList.remove('active');
    }, 200); // 延迟隐藏以便用户点击下拉框内容
  });

document.addEventListener("DOMContentLoaded", function () {
  // 集中管理 URL
  const urls = {
    guessLike: "./json/guesslike.json",
    audiobook: "./json/audiobook.json",
    ranking: "./json/ranking.json",
  };

  const guessList = document.getElementById('guess-list');
  const toggleButton = document.querySelector('.panel-head-toggle');
  let allData = [];
  let currentIndex = 0;

  // 获取数据并初始化显示
  fetchData(urls.guessLike, (data) => {
    allData = data;
    renderData();
  });

  // 渲染数据
  function renderData() {
    const displayData = allData.slice(currentIndex, currentIndex + 5);
    renderList(guessList, displayData, (item) => `
      <li>
        <a href="#" class="album-item">
          <div class="album-item-box">
            <img class="img" src="${item.img}" alt="${item.title}" />
          </div>
          <p class="album-item-tit">${item.title}</p>
          <p class="album-item-aut">${item.author}</p>
        </a>
      </li>
    `);
  }

  // 在换一批和分类点击事件中，阻止页面滚动到顶部
  const preventScrollToTop = (event) => {
    event.preventDefault();
  };

  // 修改换一批按钮的点击事件
  toggleButton.addEventListener("click", function (event) {
    preventScrollToTop(event);
    currentIndex += 5;
    if (currentIndex >= allData.length) {
      currentIndex = 0;
    }
    renderData();
  });

  const categoriesContainer = document.getElementById('audiobook-categories');
  const audiobookList = document.getElementById('audiobook-list');
  const categoryNameMap = {
    toutuoyuan: "头陀渊",
    doupocangqiong: "斗破苍穹",
    xinghancanlan: "星汉灿烂",
    santi: "三体"
  };

  fetchData(urls.audiobook, (data) => {
    const categories = Object.keys(data);
    // 读取本地存储的分类
    const savedCategory = localStorage.getItem('audiobookCategory');
    let activeCategory = savedCategory && categories.includes(savedCategory) ? savedCategory : categories[0];
    renderList(categoriesContainer, categories, (category) => {
      const displayName = categoryNameMap[category] || category;
      // 高亮active分类
      return `<li><a href="#" data-category="${category}" class="${category === activeCategory ? 'active' : ''}">${displayName}</a></li>`;
    });
    renderAudiobooks(data[activeCategory]);

    categoriesContainer.addEventListener("click", (event) => {
      if (event.target.tagName === 'A') {
        preventScrollToTop(event);
        const category = event.target.dataset.category;
        // 切换高亮
        categoriesContainer.querySelectorAll('a').forEach(a => a.classList.remove('active'));
        event.target.classList.add('active');
        // 渲染内容
        renderAudiobooks(data[category]);
        // 记忆当前分类
        localStorage.setItem('audiobookCategory', category);
      }
    });
  });

  function renderAudiobooks(audiobooks) {
    renderList(audiobookList, audiobooks, (item) => `
      <li>
        <a href="#" class="album-item">
          <div class="album-item-box">
            <img class="img" src="${item.img}" alt="${item.text}" />
          </div>
          <p class="album-item-tit">${item.text}</p>
          <p class="album-item-aut">${item.author}</p>
        </a>
      </li>
    `);
  }

  fetchData(urls.ranking, (data) => {
    updateRankingList(data);
  }, (error) => {
    console.error('Error fetching ranking.json:', error);
  });

  
  // 有声书新品榜的渲染逻辑
  const updateRankingList = (data) => {
    const rankingList = document.getElementById('ranking-list');
    rankingList.innerHTML = '';
    let noImageIndex = 4; // 从编号4开始
    data.forEach((item) => {
      const li = document.createElement('li');
      li.className = item.img ? 'list-items' : 'list-items no-img';
      li.innerHTML = `
        ${!item.img ? `<span class="num">${noImageIndex++}</span>` : ''}
        <div class="list-items-img">
          ${item.img ? `<img src="${item.img}" alt="${item.desc || '无描述'}" />` : ''}
        </div>
        <div class="list-items-txt">
          <p class="list-items-desc">${item.desc || '无描述'}</p>
          ${item.author ? `<p class="list-items-author">${item.author}</p>` : ''}
        </div>
      `;
      rankingList.appendChild(li);
    });
  };
});